package com.proton.carepatchtemp.application;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Keep;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.taobao.sophix.PatchStatus;
import com.taobao.sophix.SophixApplication;
import com.taobao.sophix.SophixEntry;
import com.taobao.sophix.SophixManager;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class SophixStubApplication extends SophixApplication {
    private static final String TAG = "SophixStubApplication";
    /**
     * 维护Activity 的list
     */
    public static List<Activity> mActivitys = Collections.synchronizedList(new LinkedList<Activity>());
    private static SophixStubApplication mInstance;

    /**
     * get current Activity 获取当前Activity（栈中最后一个压入的）
     */
    public static Activity currentActivity() {
        if (mActivitys == null || mActivitys.isEmpty()) {
            return null;
        }
        return mActivitys.get(mActivitys.size() - 1);
    }

    /**
     * 结束当前Activity（栈中最后一个压入的）
     */
    public static void finishCurrentActivity() {
        if (mActivitys == null || mActivitys.isEmpty()) {
            return;
        }
        Activity activity = mActivitys.get(mActivitys.size() - 1);
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public static void finishActivity(Activity activity) {
        if (mActivitys == null || mActivitys.isEmpty()) {
            return;
        }
        if (activity != null) {
            mActivitys.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public static void finishActivity(Class<?> cls) {
        if (mActivitys == null || mActivitys.isEmpty()) {
            return;
        }
        Iterator<Activity> iterable = mActivitys.iterator();
        Activity activity;
        while (iterable.hasNext()) {
            activity = iterable.next();
            if (activity.getClass().getSimpleName().equals(cls.getSimpleName())) {
                activity.finish();
                iterable.remove();
            }
        }
    }

    public static void finishOthersActivity(Class<?> cls) {
        for (int i = 0; i < mActivitys.size(); i++) {
            if (!mActivitys.get(i).getClass().getName().equalsIgnoreCase(cls.getName())) {
                finishActivity(mActivitys.get(i));
            }
        }
    }

    public static boolean hasActivity(Class<?> clazz) {
        for (int i = 0; i < mActivitys.size(); i++) {
            if (mActivitys.get(i).getClass().getName().equalsIgnoreCase(clazz.getName())) {
                return true;
            }
        }

        return false;
    }

    /**
     * 按照指定类名找到activity
     */
    public static Activity findActivity(Class<?> cls) {
        Activity targetActivity = null;
        if (mActivitys != null) {
            for (Activity activity : mActivitys) {
                if (activity.getClass().equals(cls)) {
                    targetActivity = activity;
                    break;
                }
            }
        }
        return targetActivity;
    }

    /**
     * 结束所有Activity
     */
    public static void finishAllActivity() {
        if (mActivitys == null) {
            return;
        }
        for (Activity activity : mActivitys) {
            activity.finish();
        }
        mActivitys.clear();
    }

    /**
     * 退出应用程序
     */
    public static void appExit() {
        try {
            Log.d(TAG, "app exit");
            finishAllActivity();
        } catch (Exception e) {
        }
    }

    public static SophixStubApplication getInstance() {
        return mInstance;
    }

    /**
     * get version code
     *
     * @param context context
     * @return version code
     */
    public static String getAppVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * get app version code
     */
    public static String getAppVersionCode(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode + "";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        registerActivityListener();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
        initHotFix();
    }

    private void initHotFix() {
        SophixManager.getInstance().setContext(this)
                .setEnableDebug(true)
                .setAppVersion(getAppVersion(this) + "." + getAppVersionCode(this))
                .setPatchLoadStatusStub((mode, code, info, handlePatchVersion) -> {
                    // 补丁加载回调通知
                    if (code == PatchStatus.CODE_LOAD_SUCCESS) {
                        // 表明补丁加载成功
                        Log.e(TAG, "load success");
                    } else if (code == PatchStatus.CODE_LOAD_RELAUNCH) {
                        // 表明新补丁生效需要重启. 开发者可提示用户或者强制重启;
                        // 建议: 用户可以监听进入后台事件, 然后应用自杀
                        Log.e(TAG, "load success restart");
                    } else if (code == PatchStatus.CODE_LOAD_FAIL) {
                        // 内部引擎异常, 推荐此时清空本地补丁, 防止失败补丁重复加载
                        Log.e(TAG, "load fail");
                        SophixManager.getInstance().cleanPatches();
                    } else {
                        // 其它错误信息, 查看PatchStatus类说明
                        Log.e(TAG, "load fail---code = " + code);
                    }
                }).initialize();
    }

    /**
     * @param activity 作用说明 ：添加一个activity到管理里
     */
    public void pushActivity(Activity activity) {
        mActivitys.add(activity);
        Log.e(TAG, "activityList:size:" + mActivitys.size());
    }

    /**
     * @param activity 作用说明 ：删除一个activity在管理里
     */
    public void popActivity(Activity activity) {
        mActivitys.remove(activity);
        Log.d(TAG, "activityList:size:" + mActivitys.size());
    }

    /**
     * @return 作用说明 ：获取当前最顶部activity的实例
     */
    public Activity getTopActivity() {
        Activity mBaseActivity = null;
        synchronized (mActivitys) {
            final int size = mActivitys.size() - 1;
            if (size < 0) {
                return null;
            }
            mBaseActivity = mActivitys.get(size);
        }
        return mBaseActivity;

    }

    /**
     * @return 作用说明 ：获取当前最顶部的acitivity 名字
     */
    public String getTopActivityName() {
        Activity mBaseActivity = null;
        synchronized (mActivitys) {
            final int size = mActivitys.size() - 1;
            if (size < 0) {
                return null;
            }
            mBaseActivity = mActivitys.get(size);
        }
        return mBaseActivity.getClass().getName();
    }

    private void registerActivityListener() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                //监听到 Activity创建事件 将该 Activity 加入list
                pushActivity(activity);
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                if (null == mActivitys || mActivitys.isEmpty()) {
                    return;
                }
                if (mActivitys.contains(activity)) {
                    //监听到 Activity销毁事件 将该Activity 从list中移除
                    popActivity(activity);
                }
            }
        });
    }

    /**
     * 此处SophixEntry应指定真正的Application，并且保证RealApplicationStub类名不被混淆。
     */
    @Keep
    @SophixEntry(VCare.class)
    static class RealApplicationStub {
    }
}